package com.mimo.admin.controller.user;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mimo.admin.proxy.MetricProxy;
import com.mimo.common.logic.user.dto.UserDTO;
import com.mimo.common.logic.user.dto.UserQueryCriteria;
import com.mimo.common.result.CollectionResult;
import com.mimo.common.result.CommonDTOResult;
import com.mimo.common.utils.JsonUtils;

import io.swagger.annotations.ApiOperation;

/**
 * 
 * @date 2021/1/26 17:49
 * @description
 **/
@RestController
@RequestMapping("/user")
public class UserController {

  private static final String DEVICE_MAPPING_PATH = "mapping/device-mapping.json";
  private static final String DEVICE_UNKNOWN = "unknown";
  private static final String DEVICE_IOS = "IOS";

  @Autowired
  private MetricProxy metricProxy;

  @PostMapping("/list")
  @ApiOperation(value = "用户列表", notes = "用户成员")
  public CollectionResult<UserDTO> list(@RequestBody UserQueryCriteria criteria) {

    criteria.setPage(criteria.getPage() - 1);
    return metricProxy.queryUser(criteria);
  }

  @PostMapping("/detail")
  @ApiOperation(value = "用户详情信息", notes = "用户详情信息")
  public CommonDTOResult<UserDTO> detail(@RequestParam String userId) {

    UserDTO userDTO = metricProxy.loadUser(userId).getDetail();
    if (Objects.nonNull(userDTO) && StringUtils.equals(userDTO.getDevice().getTerminal(), DEVICE_IOS)) {
      String model = this.convertDevice(userDTO.getDevice().getModel());
      userDTO.getDevice().setModel(model);
    }
    return new CommonDTOResult<>(userDTO);
  }

  private String convertDevice(String device) {

    try {
      InputStream inputStream = new ClassPathResource(DEVICE_MAPPING_PATH).getInputStream();
      String mapping = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
      Map<String, String> map = JsonUtils.parseJson(mapping, Map.class);
      String deviceMapping = map.get(device);
      device = '(' + device + ')';
      return StringUtils.isEmpty(deviceMapping) ? device + DEVICE_UNKNOWN : device + deviceMapping;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return device + DEVICE_UNKNOWN;
  }

}
